# -*- coding: utf-8 -*-
# Create your views here.
import logging
from django.shortcuts import render_to_response
from django.template.context import RequestContext
import os
from django.http import HttpResponse
import datetime
from google.appengine.ext import db
from com.jumang.model.note import note
from com.jumang.model.uploadfile import file
from com.jumang.model.uploadpicture import Picture
from com.jumang.model.NoteCategory import NoteCategory
from com.jumang.model.FileCategory import FileCategory,PictureCategory
from config import JumConfig,realConfig
from com.jumang.feeds.xmlrpc import dispatcher
from com.jumang.feeds.forms import TrackBackForm

def rss2(request):
    return allFeed(request,'feeds/rss2.xml')
def atom(request):
    return allFeed(request,'feeds/atom.xml')
def dwd(request):
    return allFeed(request,'feeds/atom.xml',500)
    
def allFeed(request,xmlName,size=7):
    query=db.Query(note)
    query.filter('isPublic',True)
    query.order('-createTime')
    result=query.fetch(size)
    
    values={'notes':result}
    config=realConfig
##    logging.warning(request.GET)
    config.currentHome='http://'+request.environ['HTTP_HOST']+'/'
    values['config']=config
    return render_to_response(xmlName,values)

def sitemap(request):
    values={}
    config=realConfig
    config.currentHome='http://'+request.environ['HTTP_HOST']+'/'
    values['config']=config
    values['notes']=note.all().order('-createTime')
    values['categories']=NoteCategory.all()
    values['files']=file.all().order('-createTime')
    values['fileCategories']=FileCategory.all()
    values['pictures']=Picture.all().order('-createTime')
    values['pictureCategories']=PictureCategory.all()
    return render_to_response('sitemap.xml',values)

def robot(request):
    values={}
    config=realConfig
    config.currentHome='http://'+request.environ['HTTP_HOST']+'/'
    values['config']=config
    return render_to_response('robots.txt',values)

def callApi(request):
##    logging.warning(request.POST)
##    logging.warning(request.raw_post_data)
    realConfig.currentHome='http://'+request.environ['HTTP_HOST']+'/'
    response = dispatcher._marshaled_dispatch(request.raw_post_data)
##    logging.warning(response)
    return HttpResponse(response)
  
def trackBack(request,id=''):
##    logging.warning(request.POST)
    form=TrackBackForm(request.POST)
    values={}
    if form.is_valid():
        trackBack=form.save()
        myNote=note.get_by_id(int(id))
        if myNote:
          trackBack.note=myNote
          trackBack.put()
          values['result']='0'
        else:
          values['result']='1'
          values['errorMessage']='Note is invalid!'
    else:
        values['result']='1'
        values['errorMessage']='URL is needed!'
    return render_to_response('feeds/trackback.xml',values)


